#!/usr/bin/env php
<?php

require_once __DIR__ . '/_bootstrap.php';

echo 'Creating sample image... ';
$imageWidth = 8;
$imageHeight = 16;
$image = imagecreatetruecolor($imageWidth, $imageHeight);
echo "done.\n";

$formats = [
    'gd2',
    'gif',
    'jpeg',
    'png',
    'wbmp',
    'webp',
    'wbmp',
    'xbm',
    'xpm',
    'gd',
];
if (PHP_VERSION_ID >= 70200) {
    $formats[] = 'bmp';
    if (PHP_VERSION_ID >= 80100) {
        $formats[] = 'avif';
    }
}
$tempFile = null;
$image2 = null;

function destroyImage($img)
{
    if (PHP_VERSION_ID < 80000) {
        imagedestroy($img);
    }
}

try {
    foreach ($formats as $format) {
        echo "Checking format {$format}... ";
        $loadFuntion = "imagecreatefrom{$format}";
        if (!function_exists($loadFuntion)) {
            throw new Exception("{$loadFuntion}() function is missing");
        }
        $saveFuntion = "image{$format}";
        if (!function_exists($saveFuntion)) {
            if ($format === 'xpm') {
                echo "skipping tests since PHP can't save images to that format.\n";

                continue;
            }

            throw new Exception("{$saveFuntion}() function is missing");
        }
        $tempFile = tempnam(sys_get_temp_dir(), 'dpei');
        ob_start();
        if ($saveFuntion($image, $tempFile) === false) {
            throw new Exception("{$saveFuntion}() failed");
        }
        $contents = ob_get_contents();
        ob_end_clean();
        if (!is_file($tempFile)) {
            throw new Exception("{$saveFuntion}() didn't create a file");
        }
        if (filesize($tempFile) < 1) {
            if ($format !== 'xbm' || PHP_VERSION_ID >= 50600 || $contents === '') {
                throw new Exception("{$saveFuntion}() created an empty file");
            }
            file_put_contents($tempFile, $contents);
        }
        $image2 = $loadFuntion($tempFile);
        unlink($tempFile);
        $tempFile = null;
        if (!(is_resource($image2) || is_object($image2)) || imagesx($image2) !== $imageWidth || imagesy($image2) !== $imageHeight) {
            throw new Exception("{$loadFuntion}() failed");
        }
        destroyImage($image2);
        echo "done.\n";
    }
    if (!function_exists('imagefttext')) {
        throw new Exception('imagefttext() function is missing');
    }
    if (!function_exists('imageantialias')) {
        throw new Exception('imageantialias() function is missing');
    }
    $rc = 0;
} catch (Exception $x) {
    $rc = 1;
    fwrite(STDERR, $x->getMessage());
} catch (Throwable $x) {
    $rc = 1;
    fwrite(STDERR, $x->getMessage());
} finally {
    destroyImage($image);
    if (is_resource($image2)) {
        destroyImage($image2);
    }
    if ($tempFile !== null) {
        unlink($tempFile);
    }
}
exit($rc);
